<template>
  <div class="login-container">
    <!-- vant组件导航栏 -->
   <van-nav-bar title="登录">
    <template #left>
      <img src="@/assets/images/logo.png" alt="" class="logo">
    </template>
   </van-nav-bar>
    <van-form @submit="onSubmitFn">
      <van-field
        v-model="formLogin.mobile"
        type="tel"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="[{ required: true, message: '请填写手机号', trigger: 'onChange'  },
        { pattern: /^1[3-9]\d{9}$/, message: '请填写合法的手机号',  trigger: 'onChange' }
        ]"
      />
      <van-field
        v-model="formLogin.code"
        type="password"
        label="密码"
        placeholder="请输入密码"
        required
        :rules="[{ required: true, message: '请填写验证码', trigger: 'onChange', },
        { pattern: /^\d{6}$/ ,  message: '请填写正确的验证码',  trigger: 'onChange'}
        ]"
      />
      <div style="margin: 16px;">
        <van-button :loading="loading" block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { loginAPI } from '@/api/login.js'
export default {
  name: 'Login',
  data () {
    return {
      loading: false, // 登录按钮的加载状态,默认false表示没有加载
      formLogin: {
        mobile: '15301303920',
        code: '246810' // 默认只能用246810后台规定了
      }
    }
  },
  methods: {
    ...mapMutations('user', ['setToken', 'setRefreshToken']),
    async onSubmitFn () {
      this.loading = true
      try {
        const res = await loginAPI({
          tel: this.formLogin.mobile,
          pwd: this.formLogin.code
        })
        this.loading = false
        // console.log(res)
        // 拿到token和refresh_token,提交到mutation即可(解构)
        const { token, refresh_token: refreshToken } = res.data
        this.setToken(token)
        this.setRefreshToken(refreshToken)
        this.$toast.success('登录成功')
        // replace 表示跳转后不能回退, push可以回退
        this.$router.replace(this.$route.query.redirect || '/layout')
      } catch (e) {
        this.$toast.fail('登录出错')
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.logo {
  width: 100px;
  height: 30px;
}

</style>
